<!-- 消息框 -->
<template>
  <div v-loading="listLoading" class="message">
    <header class="header">
      <div class="friendname">{{ Names }}</div>
      <div class="hzxx">
        <el-popover
          placement="bottom"
          width="400"
          trigger="click"
        >
          <el-descriptions title="患者信息" border>
            <el-descriptions-item label="姓名">{{ Names }}</el-descriptions-item>

            <el-descriptions-item label="性别">{{ Sexs }}</el-descriptions-item>

            <el-descriptions-item label="年龄">{{ Ages }}</el-descriptions-item>
          </el-descriptions>
          <div slot="reference">
            <i class="el-icon-user" />
            <i class="el-icon-arrow-down" />
          </div>
        </el-popover>
      </div>

    </header>
    <div ref="list" class="message-wrapper" @scroll="handleScroll()">
      <div v-if="iconLoading" style="text-align: center;">
        <i class="el-icon-loading" />
      </div>

      <ul v-if="selectedChat" style="min-height: 101%;">
        <li v-for="(item,index) in lists" :id="`list-${index}`" :key="index" class="message-item">
          <div class="time">
            <span v-if="item.create_time == '' ? false : true ">{{ item.create_time }}</span>
          </div>
          <div class="main" :class="{ self: item.role }">
            <!-- <img class="avatar" width="36" height="36" :src="item.self ? user.img : selectedChat.user.img"> -->
            <img
              class="avatar"
              width="36"
              height="36"
              :src="item.role ? tx : item.avatar"
            >
            <div class="content">
              <div v-if="item.typedate === 0" class="text" v-html="replaceFace(item.text)" />
              <div v-if="item.typedate !== 0" class="text">
                <img :src="item.upload_picture_list" style="max-width:100%">
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState, mapActions } from 'vuex'
import { twenDialog, surgeryQaList } from '@/api/interrogation'
import { connectWebsocket } from '@/utils/websockets'
import { getWsUrl } from '@/utils/encrypt/method'

export default {
  data() {
    return {
      list: '',
      lists: [],
      Names: '',
      Sexs: '',
      Ages: '',
      listLoading: false,
      iconLoading: false,
      page: 0,
      Wscroll: false // 判断是否因下拉加载改变list
    }
  },
  computed: {
    ...mapGetters(['selectedChat']),
    ...mapState(['user', 'emojis', 'selectId', 'watch', 'info']),
    tx() {
      const tx = JSON.parse(localStorage.getItem('doctor_info'))
      // advertisement
      return tx.data.advertisement
    }
  },
  watch: {
    // 发送信息后,让信息滚动到最下面
    list() { // 消息变化监听
      setTimeout(
        () => (this.$refs.list.scrollTop = this.$refs.list.scrollHeight),
        100
      )
    },
    selectedChat() { // 切换对话框触发
      this.page = this.selectedChat.totalPage
      console.log('触发监听', this.selectedChat, this.watch)
      if (this.watch !== false) {
        this.listLoading = true
        const id = this.selectedChat.orderid // 订单号
        this.getList(id)
        this.createds(id)

        // setTimeout(() => {
        //   this.listLoading = false
        // }, 1500)
      }
    }
  },
  created() {
    this.id = this.$route.query.id
  },
  mounted() {

  },
  methods: {
    ...mapActions(['get_info']),
    //  在发送信息之后，将输入的内容中属于表情的部分替换成emoji图片标签
    //  再经过v-html 渲染成真正的图片
    replaceFace(con) {
      if (con.includes('/:')) {
        var emojis = this.emojis
        for (var i = 0; i < emojis.length; i++) {
          con = con.replace(
            emojis[i].reg,
            '<img src="static/emoji/' +
              emojis[i].file +
              '"  alt="" style="vertical-align: middle; width: 24px; height: 24px" />'
          )
        }
        return con
      }
      return con
    },
    getList: function(id) {
      const totalPage = this.selectedChat.totalPage // 总页数
      if (this.selectedChat.v_status === 1) {
        var bizcontent = {
          doctor_auth_token: this.$store.getters.token,
          id: id,
          page: this.page,
          pagesize: 50
        }
        surgeryQaList(bizcontent)
          .then(res => {
            if (res) {
              if (this.page !== totalPage) { // 当前请求页不等于总页数--判定下拉加载请求
                for (let i = 49; i > -1; i--) {
                  this.lists.unshift(res.data.list[i])
                }
                this.$nextTick(() => {
                  document.querySelector(`#list-${50}`).scrollIntoView(true)
                })
                return
              }
              console.log(res.data)
              this.Names = res.data.info.names
              this.Sexs = res.data.info.sex
              this.Ages = res.data.info.age
              this.lists = res.data.list
              this.get_info(res.data.info)
              setTimeout(() => {
                this.$refs.list.scrollTop = this.$refs.list.scrollHeight
                this.listLoading = false
              }, 100)
            }
          })
      }
      if (this.selectedChat.v_status === 2) {
        var bizcontent2 = {
          doctor_auth_token: this.$store.getters.token,
          id: id,
          page: this.page,
          pagesize: 50
        }
        twenDialog(bizcontent2).then(res => {
          if (res) {
            if (this.page !== totalPage) { // 当前请求页不等于总页数--判定下拉加载请求
              for (let i = 49; i > -1; i--) {
                this.lists.unshift(res.data.list[i])
              }
              this.$nextTick(() => {
                document.querySelector(`#list-${50}`).scrollIntoView(true)
              })
              return
            }
            console.log(res.data, this.Wscroll)
            this.Names = res.data.info.names
            this.Sexs = res.data.info.sex
            this.Ages = res.data.info.age
            this.lists = res.data.list
            this.get_info(res.data.info)
            setTimeout(() => {
              this.$refs.list.scrollTop = this.$refs.list.scrollHeight
              this.listLoading = false
            }, 100)
          }
        })
      }
    },
    createds(id) {
      if (this.selectedChat.v_status === 1) {
        connectWebsocket(
          getWsUrl(),
          // 发送
          'doc_wenz_qa_' + id,
          // 成功拿到后台返回的数据的回调函数
          (data) => {
            console.log('wenz接收的', JSON.parse(data))
            // const orderid = this.$route.query.orderid
            const ids = this.$route.query.id
            this.$emit('AskgetList', ids, this.selectId)
            this.getList(id)
            // this.searchedChatlist()
            // this.sendText(allopatric)
          },
          // websocket连接失败的回调函数
          () => {
            console.log('失败的回调函数')
          })
      }
      if (this.selectedChat.v_status === 2) {
        connectWebsocket(
          getWsUrl(),
          // 发送
          'doc_twen_qa_' + id,
          // 成功拿到后台返回的数据的回调函数
          (data) => {
            console.log('twen接收', JSON.parse(data))
            // const datas = JSON.parse(data)
            // if (datas.type === 'qa') {
            const ids = this.$route.query.id
            this.$emit('AskgetList', ids, this.selectId, this.selectedChat.v_status)
            // }
            this.getList(id)
            // this.sendText(allopatric)
            // this.selectedChat()
          },
          // websocket连接失败的回调函数
          () => {
            console.log('失败的回调函数')
          })
      }
    },
    handleScroll() {
      const getScrollTop = this.getScrollTop()
      if (getScrollTop === 0) { // 到达顶部执行
        this.iconLoading = true
        this.page--
        if (this.page <= 0) {
          setTimeout(() => {
            console.log('已加载全部')
            this.iconLoading = false
          }, 1000)
          return
        }
        const id = this.selectedChat.orderid // 订单号
        const totalPage = this.selectedChat.totalPage // 总页数
        this.getList(id)
        setTimeout(() => {
          console.log('顶部', totalPage)
          this.iconLoading = false
        }, 1000)
      }
    },
    getScrollTop() {
      var scrollTop = 0
      var bodyScrollTop = 0
      var documentScrollTop = 0
      if (document.body) {
        bodyScrollTop = document.body.scrollTop
      }
      if (document.documentElement) {
        documentScrollTop = this.$refs.list.scrollTop
      }
      scrollTop =
                bodyScrollTop - documentScrollTop > 0
                  ? bodyScrollTop
                  : documentScrollTop
      return scrollTop
    },
    sendText(params) { // 判定发送新消息滚动
      this.list = params
      this.lists = [...this.lists, params]
    }

  },
  // eslint-disable-next-line vue/order-in-components
  filters: {
    // 将日期过滤为 hour:minutes
    time(date) {
      if (typeof date === 'string') {
        date = new Date(date)
      }
      if (date.getMinutes() < 10) {
        return date.getHours() + ':0' + date.getMinutes()
      } else {
        return date.getHours() + ':' + date.getMinutes()
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.message {
  width: 100%;
  height: 75%;

  .header {
    height: 10%;
    padding: 28px 30px 0;
    box-sizing: border-box;
    border-bottom: 1px solid #e7e7e7;
    display: flex;
    justify-content: space-between;

    .friendname {
      font-size: 18px;
    }
  }

  .message-wrapper {
    // min-height: 390px
    // max-height: 390px
    height: 90%;
    padding: 10px 15px;
    box-sizing: border-box;
    overflow-y: auto;
    border-bottom: 1px solid #e7e7e7;

    .message {
      margin-bottom: 15px;
    }

    .time {
      width: 100%;
      font-size: 12px;
      margin: 7px auto;
      text-align: center;

      span {
        display: inline-block;
        padding: 4px 6px;
        color: #fff;
        border-radius: 3px;
        background-color: #dcdcdc;
      }
    }

    .main {
      .avatar {
        float: left;
        margin-left: 15px;
        border-radius: 3px;
      }

      .content {
        display: inline-block;
        margin-left: 10px;
        position: relative;
        padding: 6px 10px;
        max-width: 330px;
        min-height: 36px;
        line-height: 24px;
        box-sizing: border-box;
        font-size: 14px;
        text-align: left;
        word-break: break-all;
        background-color: #fafafa;
        border-radius: 4px;

        &:before {
          content: ' ';
          position: absolute;
          top: 12px;
          right: 100%;
          border: 6px solid transparent;
          border-right-color: #fafafa;
        }
      }
    }

    .self {
      text-align: right;

      .avatar {
        float: right;
        margin: 0 15px;
      }

      .content {
        background-color: #b2e281;

        &:before {
          right: -12px;
          vertical-align: middle;
          border-right-color: transparent;
          border-left-color: #b2e281;
        }
      }
    }
  }
}
</style>
